package com.fallsvc.order.service;

import com.fallsvc.order.mapper.OrderMapper;
import com.fallsvc.order.model.OrderInfo;
import com.fallsvc.order.model.ProductInfo;


import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther falls_vc
 * description:
 * @date 2025/5/25  11:03
 */
@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    // 计数器
    private AtomicInteger count=new AtomicInteger(1);

    private List<ServiceInstance> instances;// 固定实例顺序

    @PostConstruct
    public void inti() {
        instances=discoveryClient.getInstances("product-service");//  固定实例顺序

    }
    public OrderInfo selectOrderById(Integer id) {
        OrderInfo orderInfo = orderMapper.selectOrderById(id);


        String url = "http://product-service/product/" + orderInfo.getProductId();

        log.info("服务发现uri；{}", url);
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);

        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
    // 2,
//    public OrderInfo selectOrderById(Integer id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//
//        // 计算轮流的实例index
//        int index = count.getAndIncrement()%instances.size();
//
//        String uri = instances.get(index).getUri().toString();
//
//        String url = uri + "/product/" + orderInfo.getProductId();
//
//        log.info("服务发现uri；{}", uri);
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }

    // 1.
//        public OrderInfo selectOrderById(Integer id) {
//        OrderInfo orderInfo = orderMapper.selectOrderById(id);
//
//        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
//        String uri = instances.get(0).getUri().toString();
//
//        String url=uri+"/product/"+orderInfo.getProductId();
//
//        log.info("服务发现uri；{}",uri);
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }
}
